package com.sx.zongzhi.adapter;


import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.sx.zongzhi.R;
import com.sx.zongzhi.bean.PhotoBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 多图选择器
 */
public class MultiImageAdapter extends RecyclerView.Adapter<MultiImageAdapter.ViewHolder> {
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;
    private LayoutInflater mInflater;
    private List<PhotoBean> list = new ArrayList<>();
    private int selectMax = 3;
    private Context context;
    /**
     * 点击添加图片跳转
     */
    private AddPicClickListener mAddPicClickListener;

    public interface AddPicClickListener {
        void onAddPicClick();
    }


    public MultiImageAdapter(Context context, AddPicClickListener mAddPicClickListener) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
        this.mAddPicClickListener = mAddPicClickListener;
    }


    public void setList(List<PhotoBean> list) {
        this.list = list;
    }

    public TextView tv_num;
    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView mImg;
        ImageView im_del;
        ImageView tv_duration;
        LinearLayout ll_bottom;
        public ViewHolder(View view) {
            super(view);
            mImg = (ImageView) view.findViewById(R.id.imageView);
            im_del = (ImageView) view.findViewById(R.id.iv_del);
            tv_duration = (ImageView) view.findViewById(R.id.tv_duration);
            tv_num = (TextView) view.findViewById(R.id.tv_num);
            ll_bottom = (LinearLayout) view.findViewById(R.id.ll_bottom);
        }
    }

    @Override
    public int getItemCount() {
        if (list.size() < selectMax) {
            return list.size() + 1;
        } else {
            return list.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowAddItem(position)) {
            return TYPE_CAMERA;
        } else {
            return TYPE_PICTURE;
        }
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = mInflater.inflate(R.layout.item_multi_image_list,
                viewGroup, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    private boolean isShowAddItem(int position) {
        int size = list.size() == 0 ? 0 : list.size();
        return position == size;
    }

    /**
     * 设置值
     */
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        //少于8张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.mImg.setImageResource(R.mipmap.icon_upload);
            viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAddPicClickListener.onAddPicClick();
                }
            });
            viewHolder.im_del.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.im_del.setVisibility(View.VISIBLE);
            viewHolder.im_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int index = viewHolder.getAdapterPosition();
                    // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                    // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
                    if (index != RecyclerView.NO_POSITION) {
                        if (list.get(position).getPath().startsWith("http")){
                            if (mDeleteNetFileListener != null){
                                mDeleteNetFileListener.deleteFileId(list.get(position).getId());
                            }
                        }
                        if (list.get(position).getSuffixType().equals(".amr")){
                            if (mStopPlayAudioListener != null){
                                mStopPlayAudioListener.stopPlayAudio();
                            }
                        }
                        list.remove(index);
                        notifyItemRemoved(index);
                        notifyItemRangeChanged(index, list.size());
                    }
                }
            });
            PhotoBean bean = list.get(position);
            String mimeType = bean.getSuffixType();
            String path = bean.getPath();
            viewHolder.ll_bottom.setVisibility(View.VISIBLE );
            if (".wav".equalsIgnoreCase(mimeType) || ".amr".equalsIgnoreCase(mimeType)) {//音频
                if (bean.isPlay){
                    tv_num.setVisibility(View.GONE);
                    Glide.with(context).load(R.mipmap.icon_play_audio).into(viewHolder.tv_duration);
                }else {
                    tv_num.setVisibility(View.GONE);
                    viewHolder.tv_duration.setImageResource(R.mipmap.icon_audios);
                }
                viewHolder.mImg.setImageResource(R.mipmap.img_audio);
            } else if(".mp4".equalsIgnoreCase(mimeType)){//视频
                tv_num.setVisibility(View.GONE);
                viewHolder.tv_duration.setImageResource(R.drawable.video_icon);
                try {
                    MediaMetadataRetriever media = new MediaMetadataRetriever();
                    media.setDataSource(bean.getPath());
                    Bitmap bitmap = media.getFrameAtTime();
                    viewHolder.mImg.setImageBitmap(bitmap);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (".jpg".equalsIgnoreCase(mimeType)||".jpeg".equalsIgnoreCase(mimeType)||
                    ".png".equalsIgnoreCase(mimeType)){//图片
                viewHolder.ll_bottom.setVisibility(View.GONE);
                viewHolder.tv_duration.setImageResource(R.color.color_f6);
                RequestOptions options = new RequestOptions()
                        .centerCrop()
                        .placeholder(R.color.color_f6)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE);
                Glide.with(viewHolder.itemView.getContext())
                        .load(path)
                        .apply(options)
                        .into(viewHolder.mImg);
            }else {
                viewHolder.mImg.setImageResource(R.mipmap.img_file);
                viewHolder.tv_duration.setImageResource(R.color.color_f6);
            }

            //itemView 的点击事件
            if (mItemClickListener != null) {
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int adapterPosition = viewHolder.getAdapterPosition();
                        mItemClickListener.onItemClick(adapterPosition, v);
                    }
                });
            }
        }
    }

    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position, View v);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }
//停止播放录音
    protected OnStopPlayAudioClickListener mStopPlayAudioListener;
    public interface OnStopPlayAudioClickListener {
        void stopPlayAudio();
    }
    public void setOnStopPlayAudioClickListener(OnStopPlayAudioClickListener listener) {
        this.mStopPlayAudioListener = listener;
    }

    //删除网络 文件
    protected OnDeleteNetFileClickListener mDeleteNetFileListener;
    public interface OnDeleteNetFileClickListener {
        void deleteFileId(String fileId);
    }
    public void setOnDeleteNetFileClickListener(OnDeleteNetFileClickListener listener) {
        this.mDeleteNetFileListener = listener;
    }
}
